package com.qingke.servlets;

import java.io.IOException;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class CookieTest
 */
@WebServlet("/CookieTest")
public class CookieTest extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CookieTest() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.getWriter().append("Served at: ").append(request.getContextPath());
		// COOKIES
		// 从request中取cookie
		Cookie[] myCookies = request.getCookies();
		if (myCookies == null) {
			myCookies = new Cookie[0];
		}
		for (Cookie cookie : myCookies) {
			System.out.println(cookie.getName() + " = " + cookie.getValue());
		}
		String sessionId = request.getSession().getId();
		Calendar calendar = Calendar.getInstance();
		Cookie cookie1 = new Cookie("mySessionId", sessionId);
		// cookie过期时间，默认为-1，直到浏览器关闭才过期
		//与request.getSession().setMaxInactiveInterval()等效
		cookie1.setMaxAge(60);
		// 创建cookie
		Cookie cookie2 = new Cookie("myTime", String.valueOf(calendar.getTimeInMillis()));
		// 将cookie加入response
		response.addCookie(cookie1);
		response.addCookie(cookie2);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
